package com.struts;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ActionServlet extends HttpServlet {

	private static final long serialVersionUID = -6299452302107650078L;

	public ActionServlet() {
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		String servletPath=request.getServletPath();
		String actionPath=servletPath.substring(1, servletPath.length()-3);
		
		Map<String,ActionBean> map = (Map<String, ActionBean>) request.getSession().getServletContext().getAttribute("actionConfig");
		ActionBean actionBean=map.get(actionPath);
		
		String actionClass= actionBean.getActionClass();
		BaseAction action=this.fillAction(actionClass);
		
		String formClass=actionBean.getFormClass();
		BaseActionForm form=this.fillActionForm(formClass, request);
		
		String resultName=action.execute(request, response, form);
		
		String resultValue=actionBean.getResultMap().get(resultName);
		
		request.getRequestDispatcher(resultValue).forward(request, response);
	}
	
	public BaseActionForm fillActionForm(String className,HttpServletRequest request){
		BaseActionForm actionFrom=null;
		try {
			Class clazz=Class.forName(className);
			actionFrom =(BaseActionForm) clazz.newInstance();
			Field[] field_arr=actionFrom.getClass().getDeclaredFields();
			for(Field f:field_arr){
				f.setAccessible(true);
				f.set(actionFrom, request.getParameter(f.getName()));
				f.setAccessible(false);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		
		return actionFrom;
	}
	
	public BaseAction fillAction(String className){
		BaseAction action = null;
		
		try {
			Class clazz=Class.forName(className);
			action=(BaseAction) clazz.newInstance();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		
		return action;
	}
	
}
